package top.chengdongqing.mishop.order.payment

import jakarta.servlet.http.HttpServletRequest
import org.springframework.data.repository.findByIdOrNull
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.*
import top.chengdongqing.mishop.enums.OrderStatus
import top.chengdongqing.mishop.enums.PaymentMethod
import top.chengdongqing.mishop.repositories.OrderEventRepository
import top.chengdongqing.mishop.repositories.OrderRepository
import top.chengdongqing.mishop.utils.IpUtils
import java.time.LocalDateTime

@RestController
@RequestMapping("/orders/payment")
class PaymentController(
    private val paySuccessNotifier: PaySuccessHandler,
    private val orderRepository: OrderRepository,
    private val orderEventRepository: OrderEventRepository
) {

    @GetMapping("/{orderId}/{paymentMethod}")
    fun payOrder(
        @AuthenticationPrincipal userId: Int,
        @PathVariable orderId: Int,
        @PathVariable paymentMethod: PaymentMethod,
        request: HttpServletRequest
    ): String {
        // TODO 请求支付
        return IpUtils.getClientIP(request)
    }

    @PostMapping("/callback/alipay")
    fun handleAlipayCallback(@RequestParam orderId: Int): String {
        // TODO
        handlePaySuccess(orderId, PaymentMethod.ALIPAY)
        return "支付宝支付回调"
    }

    @PostMapping("/callback/wechat")
    fun handleWechatCallback(@RequestParam orderId: Int): String {
        // TODO
        handlePaySuccess(orderId, PaymentMethod.WECHAT)
        return "微信支付回调"
    }

    // 仅供测试
    private fun handlePaySuccess(orderId: Int, paymentMethod: PaymentMethod) {
        // 更新订单信息
        val paymentTime = LocalDateTime.now()
        orderRepository.findByIdOrNull(orderId)?.also {
            it.status = OrderStatus.PENDING_PACKING
            it.paymentTime = paymentTime
            it.paymentMethod = paymentMethod
            orderRepository.save(it)
        }
        orderEventRepository.findByIdOrNull(orderId)?.also {
            it.paymentAt = paymentTime
            orderEventRepository.save(it)
        }

        // 通知客户端支付成功
        paySuccessNotifier.notifyPaySuccess(orderId)
    }
}